//
//  SWDataToolKit.swift
//  ReservationClient
//
//  Created by Stan Wu on 15/3/29.
//  Copyright (c) 2015 Stan Wu. All rights reserved.
//

import Foundation
import UIKit
import AdSupport
import CommonCrypto

extension String{
    /*
    static func UUIDString() -> String{
        var UUID : String?

        let device = UIDevice.currentDevice()
        if device.respondsToSelector(Selector("identifierForVendor")) {
            UUID = ASIdentifierManager.sharedManager().advertisingIdentifier.UUIDString
        }else{
            UUID = NSUserDefaults.standardUserDefaults().objectForKey("UUID") as! String?
            if let uuidStr = UUID{
                let uuidref:CFUUIDRef = CFUUIDCreate(nil);
                let uuidstr:CFStringRef = CFUUIDCreateString(nil, uuidref);
                UUID = uuidstr as String;
                
                NSUserDefaults.standardUserDefaults().setObject(UUID!, forKey: "UUID")
            }
        }

        
        return UUID!;
    }
    */
    
    static func UUIDString() -> String{
//        var UUID : String?
        
        
       var UUID = NSUserDefaults.standardUserDefaults().objectForKey("UUID") as! String?
        if UUID == nil {
                let uuidref:CFUUIDRef = CFUUIDCreate(nil);
                let uuidstr:CFStringRef = CFUUIDCreateString(nil, uuidref);
                UUID = uuidstr as String;
                
                NSUserDefaults.standardUserDefaults().setObject(UUID!, forKey: "UUID")
        }
        
        
        
        return UUID!;
    }
        
    func HMACSHA1StringWithKey(key: String) -> String{
        let keydata = key.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) as NSData!
        let data = self.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) as NSData!
        
        let result = NSMutableData(length: Int(CC_SHA1_DIGEST_LENGTH)) as NSMutableData!
        if (result != nil) {
            CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1),
                keydata.bytes, size_t(keydata.length),
                data.bytes, size_t(data.length),
                result!.mutableBytes)
        }
        
        let resultBytes = UnsafeMutablePointer<CUnsignedChar>(result.mutableBytes)
        
        let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, count: result.length)
        
        let str = NSMutableString()
        for c in resultEnumerator {
            str.appendFormat("%02X", c)
        }
        
        return str as String;
    }
    
    func bundlePath() -> String{
        return NSBundle.mainBundle().pathForResource(self, ofType: nil)!
    }
    
    func stringByAppendingPathComponent(str: String) -> String{
        return (self as NSString).stringByAppendingPathComponent(str) as String
    }
    
    var lastPathComponent:String{
        get{
            return (self as NSString).lastPathComponent
        }
    }
    
    func imageCachePath() -> String{
    
        var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true);
        
        let imagesPath = paths[0].stringByAppendingPathComponent("images")
        
        if !NSFileManager.defaultManager().fileExistsAtPath(imagesPath){
            do {
                try NSFileManager.defaultManager().createDirectoryAtPath(imagesPath, withIntermediateDirectories: false, attributes: nil)
            } catch _ {
            }
        }
        
        if !NSUserDefaults.standardUserDefaults().boolForKey("ImageDirectoryExcluded"){
            let url = NSURL.fileURLWithPath(imagesPath)
            
            var error:NSError?
            var success: Bool
            do {
                try url.setResourceValue(NSNumber(bool: true), forKey: NSURLIsExcludedFromBackupKey)
                success = true
            } catch let error1 as NSError {
                error = error1
                success = false
            }
            
            if success{
                NSUserDefaults.standardUserDefaults().setBool(true, forKey: "ImageDirectoryExcluded")
            }
        }
        
        let path = imagesPath.stringByAppendingPathComponent(self)
        
        return path;
    }
    
    func documentPath() -> String{
        var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true);
        
        let path = paths[0].stringByAppendingPathComponent(self)
        
        return path
    }
    
    
    func temporaryPath() -> String{
        
        var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true);
        
        let imagesPath = paths[0].stringByAppendingPathComponent("tmp")
        
        if !NSFileManager.defaultManager().fileExistsAtPath(imagesPath){
            do {
                try NSFileManager.defaultManager().createDirectoryAtPath(imagesPath, withIntermediateDirectories: false, attributes: nil)
            } catch _ {
            }
        }
        
        if !NSUserDefaults.standardUserDefaults().boolForKey("TmpDirectoryExcluded"){
            let url = NSURL.fileURLWithPath(imagesPath)
            
            var error:NSError?
            var success: Bool
            do {
                try url.setResourceValue(NSNumber(bool: true), forKey: NSURLIsExcludedFromBackupKey)
                success = true
            } catch let error1 as NSError {
                error = error1
                success = false
            }
            
            if success{
                NSUserDefaults.standardUserDefaults().setBool(true, forKey: "TmpDirectoryExcluded")
            }
        }
        
        let path = imagesPath.stringByAppendingPathComponent(self)
        
        return path;
    }


}

extension NSData{
    func MD5String() -> String{
        let result:NSMutableData! = NSMutableData(length: Int(CC_MD5_DIGEST_LENGTH))

        let resultBytes = UnsafeMutablePointer<CUnsignedChar>(result.mutableBytes)
        CC_MD5(self.bytes,  UInt32(self.length),  resultBytes)
        
        let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, count: result.length)
        
        let str = NSMutableString()
        for c in resultEnumerator {
            str.appendFormat("%02X", c)
        }
        
        return str as String;
    }
    
    func SHA1String() -> String{
        let result:NSMutableData! = NSMutableData(length: Int(CC_SHA1_DIGEST_LENGTH))
        
        let resultBytes = UnsafeMutablePointer<CUnsignedChar>(result.mutableBytes)
        CC_SHA1(self.bytes,  UInt32(self.length),  resultBytes)
        
        let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, count: result.length)
        
        let str = NSMutableString()
        for c in resultEnumerator {
            str.appendFormat("%02X", c)
        }
        
        return str as String;
    }
    
    
    func hmac_sha1(data: NSData, key: NSData) -> (NSData?) {
        let result = NSMutableData(length: Int(CC_SHA1_DIGEST_LENGTH))
        if (result != nil) {
            CCHmac(CCHmacAlgorithm(kCCHmacAlgSHA1),
                key.bytes, size_t(key.length),
                data.bytes, size_t(data.length),
                result!.mutableBytes)
        }
        return result
    }
}
